﻿using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;
using RazorEngine.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CodeGenerator.Common
{
    public class RazorHelper
    {
        public static string RunCompile(string fileName, object model)
        {
            var config = Init();
            // 使用RazorEngineService.Create创建了模板引擎服务的实例，这样的好处是，当我程序运行时修改test3.cshtml文件的内容时不会抛出"键已被使用"的异常
            using (var service = RazorEngineService.Create(config))
            {
                string path = Application.StartupPath + fileName;
                string template = System.IO.File.ReadAllText(path, System.Text.Encoding.UTF8);
                
                //string result = service.RunCompile(template, string.Empty, null, model);
                string result = service.RunCompile(template, Guid.NewGuid().ToString(), null, model);
                return result;
            }
        }

        public static string RunCompile(string fileName, string key, object model)
        {
            var config = Init();
            // 使用RazorEngineService.Create创建了模板引擎服务的实例，这样的好处是，当我程序运行时修改test3.cshtml文件的内容时不会抛出"键已被使用"的异常
            using (var service = RazorEngineService.Create(config))
            {
                string path = Application.StartupPath + fileName;
                string template = System.IO.File.ReadAllText(path, System.Text.Encoding.UTF8);
               
                string result = service.RunCompile(template, key, null, model);
                return result;
            }
        }

        public static string Run(string key, object model)
        {
            string result = Engine.Razor.Run(key, null, model);
            return result;
        }

        /// <summary>
        /// 通过模版文件路径读取文件内容
        /// </summary>
        /// <param name="path">模版文件路径</param>
        /// <param name="strOutputPath">生成文件的输出路径，如c:\1.txt</param>
        /// <param name="model">模版文件的参数</param>
        public static void CreateFile(string fileName, string strOutputPath, object model)
        {
            if (String.IsNullOrEmpty(strOutputPath))
            {
                throw new ArgumentNullException("模版文件输出路径为空！");
            }
            try
            {
                string str = RunCompile(fileName, model);
                StreamWriter sw = new StreamWriter(strOutputPath, false, System.Text.Encoding.UTF8);
                sw.Write(str);
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static TemplateServiceConfiguration Init()
        {
            var config = new TemplateServiceConfiguration();
            config.Language = Language.CSharp; // C# as template language.
            config.EncodedStringFactory = new RawStringFactory(); // Raw string encoding.
            config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding.
            config.DisableTempFileLocking = true;
            //config.CachingProvider = new DefaultCachingProvider(t => { });
            config.Namespaces = new HashSet<string>() { "CodeGenerator.Core", "System.Text" };
            config.Debug = false;

            config.BaseTemplateType = typeof(MyTemplateBase<>);

            return config;
        }
    }
}
